package com.example.adminbase.shiro;

import com.alibaba.fastjson.JSON;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class JsonAuthenticationFilter extends FormAuthenticationFilter {
    public JsonAuthenticationFilter() {
    }

    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write(JSON.toJSONString(subject.getSession().getAttribute("user")));
        return false;
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        response.setContentType("application/json;charset=UTF-8");
        HttpServletResponse r = (HttpServletResponse) response;
        r.setStatus(403);
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
        } catch (IOException e1) {
            throw new RuntimeException(e1);
        }
        writer.write(JSON.toJSONString(new JsonResponse(e.getMessage())));
        return false;
    }

}
